<template>
  <div>
    <avue-form
      :option="option"
      ref="crud"
      v-model="form">
      <template slot="bomNo">
        <el-select v-model="form.bomNo" clearable remote :remote-method="remoteMethods" :loading="searchloading" filterable placeholder="请选择零件" style="width: 100%">
          <el-option v-for="item in bomNoList" :key="item.id" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </template>
      <template slot="add">
        <el-button type="primary" icon="el-icon-plus" @click="addMaterial"></el-button>
      </template>
      <template slot="info">
        <avue-crud
          ref="infoCrud"
          class="noMenuHtml"
          :option="infoOption"
          :data="childPrdBomList"
          @row-save="addSave"
          @row-update="addUpdate"
          @row-del="inforRowDel">
        </avue-crud>
      </template>
    </avue-form>
    <div class="center mt">
      <el-button icon="el-icon-circle-close" size="mini" @click="$emit('close')">取 消</el-button>
      <el-button icon="el-icon-circle-plus-outline" v-if="type=='add'" v-loading="goon" size="mini"
                 @click.stop="saveAndGoon()">保存并继续
      </el-button>
      <el-button icon="el-icon-circle-plus-outline" :loading="saveLoading" type="primary" v-show="type!='view'"
                 size="mini" @click="saveFn">保 存
      </el-button>
    </div>
  </div>
</template>

<script>
import * as product from '@/views/publicbom/bom/ajax.js';
import {getUnitList} from '@/api/basic/unit';
import {getMaterialgroupList} from '@/api/project/productData/baseData';
import {mapGetters, mapState} from 'vuex';
import {init} from '@/mixins/init';
import {infoOption} from '@/const/project/bom';

export default {
  props: ['type', 'row', 'copy'],
  data() {
    return {
      saveLoading: false,
      goon: false,
      bomHistory: false,
      bomMainData: {},
      isSuccsess: false,
      seeMaterial: false,
      currentMaterialNo: '', //当前选中的产品编码
      query: {},
      productList: [],
      bomNoList: [],
      rules: [
        {
          required: true,
          message: '请选择直接上级产品',
          trigger: 'blur',
        },
      ],
      option: {
        emptyBtn: false,
        submitBtn: false,
        group: [
          {
            label: 'BOM信息',
            prop: 'infor',
            icon: 'el-icon-edit-outline',
            column: [
              {
                label: '产品',
                prop: 'materialNo',
                filterable: true,
                disabled:false,
                type: 'select',
                dicData: [],
                span: 12,
                rules: [
                  {
                    required: true,
                    message: '请选择产品',
                    trigger: 'blur',
                  },
                ],
              },
            ],
          },
          {
            label: 'BOM组成',
            prop: 'jbxx',
            icon: 'el-icon-edit-outline',
            column: [
              {
                label: '零件类型',
                prop: 'bomMaterialType',
                type: 'cascader',
                display:true,
                span: 7,
                // cascaderItem: ['materialGroupNo'],
                dicUrl: '/api/materialinfo/getTree?code=materials&dictKey=P,M',
                // dicUrl: '/api/materialgroup/getTree?code=materials',
                props: {
                  label: 'dictValue',
                  value: 'dictKey',
                },
              },
              {
                label: '零件组',
                prop: 'materialGroupNo',
                type: 'select',
                filterable: true,
                display:true,
                span: 7,
                props: {
                  label: 'materialGroupName',
                  value: 'materialGroupNo',
                },
                // cascaderIndex: 0,
                dicData: [],
                // dicUrl: `/api/materialgroup/list?materialType={{key}}`,
              },
              {
                label: '零件',
                prop: 'bomNo',
                type: 'select',
                filterable: true,
                display:true,
                span: 7,
                formslot: true,
                dicData: [],
              },
              {
                label: '',
                labelWidth: 0,
                display:true,
                span: 3,
                prop: 'add',
                formslot: true,
              },
              {
                labelWidth: 0,
                label: '',
                prop: 'info',
                span: 24,
                formslot: true,
              },
            ],
          },
        ],
      },
      form: {
        materialNo:"",
        // materialType: [],
        // materialGroupNo: '',
      },
      infoOption: infoOption,
      childPrdBomList: [],
      materialList: [],
      BOMdata: [],
      searchloading: false,
    };
  },
  computed: {
    ...mapGetters(['permission']), //权限映射
    ...mapState({
      headers: (state) => ({'Blade-Auth': `bearer ${state.user.token}`}),
    }),
    permissionList() {
      //按钮权限设置
      return {
        addBtn: this.vaildData(this.permission.public_productbom_add, false),
        viewBtn: this.vaildData(this.permission.public_productbom_view, false),
        delBtn: this.vaildData(this.permission.public_productbom_delete, false),
        editBtn: this.vaildData(this.permission.public_productbom_edit, false),
      };
    },
    getId() {
      return this.form.id;
    },
    productDrawingNos() {
      //所有勾选的id
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.productDrawingNo);
      });
      return ids.join(',');
    },
  },
  watch: {
    'form.bomMaterialType'(newVal, oldVal) {
      if (newVal && newVal.length > 0) {
        getMaterialgroupList({materialType: newVal.join(',')}).then((res) => {
          let data = res.data.data;
          const column = this.findObject(this.option.group[1].column, 'materialGroupNo');
          if (res.data.data.length == 0) {
            column.dicData.length = 0;
            column.dicData = [];
          } else {
            column.dicData = data;
          }
        });
        product.materialList({materialType: newVal[1]}).then((res) => {
          // const column = this.findObject(this.option.group, 'bomNo');
          if (res.data.data.length == 0) {
            // column.dicData.length = 0;
            // column.dicData = [];
            this.bomNoList = []
          } else {
            this.materialList = res.data.data;
            // column.dicData = res.data.data.map((item) => {
            this.bomNoList = res.data.data.map((item) => {
              return {
                label: item.materialName + '(' + item.materialNo + ')',
                value: item.materialNo,
              };
            });
          }
        });
      }
      if (newVal && newVal.length == 0) {
        this.$set(this.form, 'materialGroupNo', null);
        this.$set(this.form, 'bomNo', null);
      }
      if (oldVal && oldVal.length > 0 && newVal && newVal.length > 0 && newVal.join(',') !== oldVal.join(',')) {
        this.$set(this.form, 'materialGroupNo', null);
        this.$set(this.form, 'bomNo', null);
      }
    },
    'form.materialGroupNo'(newVal, oldVal) {
      if (newVal) {
        this.$set(this.form, 'bomNo', null);
      }
      if (newVal && this.form.bomMaterialType.length > 0) {
        product.materialList({materialType: this.form.bomMaterialType[1], materialGroupNo: newVal}).then((res) => {
          // const column = this.findObject(this.option.group, 'bomNo');
          if (res.data.data.length == 0) {
            // column.dicData.length = 0;
            this.bomNoList = []
            // column.dicData = [];
          } else {
            this.materialList = res.data.data;
            // column.dicData = res.data.data.map((item) => {
            this.bomNoList = res.data.data.map((item) => {
              return {
                label: item.materialName + '(' + item.materialNo + ')',
                // label: item.materialName + '(' + item.specifications + '/' + item.model + ')',
                value: item.materialNo,
              };
            });
          }
        });
      }
      if (!newVal || (newVal && this.form.bomMaterialType.length == 0)) {
        this.$set(this.form, 'bomNo', null);
      }
    },
  },
  created() {
    this.query.productType = 'PC';
    if (this.type != 'add') {
      this.form = {
        ...this.row,
      }
    }
    product.bomproductList({flag: 'bom'}).then(res=>{
      let data1 = res.data.data;
      const column = this.findObject(this.option.group, 'materialNo');
      column.dicData = data1.map((item) => {
        return {
          label: item.materialName + '(' + item.materialNo + ')',
          value: item.materialNo,
        };
      });
    })
    this.beforeOpen();
  },
  methods: {
    remoteMethods(query) {
      if (query !== '') {
        this.searchloading = true;
        let params = {
          materialName: query
        }
        if (this.form.bomMaterialType[1]) {
          params.materialType = this.form.bomMaterialType[1]
        }
        if (this.form.materialGroupNo) {
          params.materialGroupNo = this.form.materialGroupNo
        }
        product.materialList(params).then(res => {
          this.materialList = res.data.data
          this.bomNoList = res.data.data.map((item) => {
            return {
              label: item.materialName + '(' + item.materialNo + ')',
              value: item.materialNo,
            }
          })
          this.searchloading = false
        }).catch(() => {
          this.bomNoList = []
          this.searchloading = false
        })
      } else {
        this.bomNoList = [];
        this.searchloading = false
      }
    },
    copyBom(row, index) {
      this.copy = true;
      this.$refs.crud.rowEdit(row, index);
    },
    addMaterial() {
      if (!this.form.bomNo) {
        this.$message.error('请选择要添加的零件');
        return;
      }
      if (this.form.bomNo) {
        if (!this.form.materialNo) {
          this.$message.error('请先选择产品');
          return;
        }
        if (this.childPrdBomList.length > 0) {
          let isHave = false;
          isHave = this.childPrdBomList.some((item) => item.materialNo == this.form.bomNo);
          if (isHave) {
            this.$message.error('零件已添加，不可重复添加');
            return;
          }
        }
        this.materialList.every((item) => {
          if (this.form.bomNo == item.materialNo) {
            if (this.form.materialNo && this.form.materialNo == this.form.bomNo) {
              this.$message.error('添加的零件不可以与产品相同');
            } else {
              item.$cellEdit = true;
              item.quota = '';
              item.lossRate = '';
              delete item.id
              this.childPrdBomList.push(item);
            }
            return false;
          } else {
            return true;
          }
        });
      }
    },
    validQuotaNoMessage(quota) {
      let reg = /^[0-9]*\/+[1-9][0-9]*$/; //分数验证
      let reg1 = /^([0-9]|[1-9][0-9])(\.\d{1,4})?$/; //100以内的整数或最多四位小数验证
      if (quota) {
        if (quota == '0') {
          return false;
        } else if (reg.test(quota)) {
          let arr = quota.split('/');
          if (arr[0] == 0 || arr[1] == 0 || arr[0] >= arr[1]) {
            return false;
          } else {
            return true;
          }
        } else if (!reg.test(quota) && !reg1.test(quota)) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    validQuota(quota) {
      let reg = /^[0-9]*\/+[1-9][0-9]*$/; //分数验证
      let reg1 = /^([0-9]|[1-9][0-9])(\.\d{1,4})?$/; //100以内的整数或最多四位小数验证
      if (quota) {
        if (quota == '0') {
          this.$message.error('定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)');
          return false;
        } else if (reg.test(quota)) {
          let arr = quota.split('/');
          if (arr[0] == 0 || arr[1] == 0 || arr[0] >= arr[1]) {
            this.$message.error('定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)');
            return false;
          } else {
            return true;
          }
        } else if (!reg.test(quota) && !reg1.test(quota)) {
          this.$message.error('定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)');
          return false;
        } else {
          return true;
        }
      } else {
        this.$message.error('请输入定额');
        return false;
      }
    },
    validLossRate(lossRate) {
      if (lossRate) {
        let valid = /^(0|[1-9]{1}|[1-9]{1}[0-9]{1})((\.\d{1,2})?)$|100$|100.00$|100.0$/.test(lossRate);
        if (valid) {
          return true;
        } else {
          this.$message.error('损耗率请输入100以内的正整数或最多两位小数');
          return false;
        }
      } else {
        this.$message.error('请输入损耗率');
        return false;
      }
    },
    addUpdate(form, index, done, loading) {
      let validQuota = this.validQuota(form.quota);
      if (validQuota) {
        let validLossRate = this.validLossRate(form.lossRate);
        if (validLossRate) {
          done();
        } else {
          loading();
        }
      } else {
        loading();
      }
    },
    inforRowDel(row, index) {
      this.childPrdBomList.splice(index, 1);
    },
    fileChange(param, type) {
      let formData = new FormData();
      formData.append('file', param.file);
      formData.append('type', '1'); //主数据
      product
        .fileUpload(formData)
        .then(() => {
          this.isSuccsess = false;
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        })
        .catch((error) => {
          console.log(error);
          this.isSuccsess = false;
          this.$refs.uploader.clearFiles();
        });
    },
    getBom() {
      product.productBomList(this.currentMaterialNo).then((res) => {
        const data = res.data.data;
        this.BOMdata = data;
      });
    },
    handleCurrentRowChange(val) {
      // debugger;
      if (val) {
        this.currentMaterialNo = val.materialNo;
        this.getBom();
      } else {
        this.BOMdata = [];
      }
    },
    handleDown() {
      // product.productInforDown();
    },
    validFunction(data) {
      let equipMsg = '';
      if (data.length == 0) {
        equipMsg = `【BOM组成】不能为空`;
        this.$message.error(equipMsg);
      } else {
        data.every((item, index) => {
          if (!item.quota) {
            equipMsg = `【BOM组成】第${index + 1}行 请输入定额`;
            this.$message.error(equipMsg);
            return false;
          } else {
            let validQuota = this.validQuotaNoMessage(item.quota);
            if (!validQuota) {
              equipMsg = `【BOM组成】第${index + 1}行 定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)`;
              this.$message.error(equipMsg);
              return false;
            }
          }
          if (!item.lossRate) {
            equipMsg = `【BOM组成】第${index + 1}行 请输入损耗率`;
            this.$message.error(equipMsg);
            return false;
          } else if (!/^(0|[1-9]{1}|[1-9]{1}[0-9]{1})((\.\d{1,2})?)$|100$|100.00$|100.0$/.test(item.lossRate)) {
            equipMsg = `【BOM组成】第${index + 1}行 损耗率请输入100以内的正整数或最多两位小数`;
            this.$message.error(equipMsg);
            return false;
          }
          return true;
        });
      }
      if (equipMsg) {
        return false;
      }
      return true;
    },
    saveFn() {
      this.$refs.crud.validate((res, done) => {
        if (res) {
          let valid = this.validFunction(this.childPrdBomList);
          if (!valid) {
            done();
            return;
          }
          if (this.type == 'add' || this.type == 'copy') {
            let children = this.childPrdBomList.map((item) => {
              if (item.id) {
                delete item.id;
              }
              return item;
            });
            this.form.dataSource = '1';
            let content = {...this.form, childPrdBomList: children};
            content.id = null;
            this.saveLoading = true;
            product.bomAdd(content).then(
              () => {
                done();
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                });
                this.$emit('reload');
                this.saveLoading = false;
              },
            ).catch(() => {
              done();
              this.saveLoading = false;
            });
          } else if (this.type == 'edit') {
            let content = {...this.form, childPrdBomList: this.childPrdBomList};
            product.bomUpdate(content).then(
              () => {
                done();
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                });
                this.$emit('reload');
                this.saveLoading = false;
              },
            ).catch(() => {
              done();
              this.saveLoading = false;
            });
          }
        }
      })
    },
    saveAndGoon() {
      this.$refs.crud.validate((res, done) => {
        if (res) {
          let valid = this.validFunction(this.childPrdBomList);
          if (!valid) {
            done();
            return;
          }
          let children = this.childPrdBomList.map((item) => {
            if (item.id) {
              delete item.id;
            }
            return item;
          });
          this.form.dataSource = '1';
          let content = {...this.form, childPrdBomList: children};
          content.id = null;
          this.goon = true;
          product.bomAdd(content).then(
            () => {
              done();
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              this.$emit('closeAfter');
              this.goon = false;
              for (let key in this.$refs.crud.value) {
                this.$refs.crud.value[key] = null;
              }
              this.$refs.crud.resetFields();
              this.childPrdBomList = [];
              this.childPrdBomList.length = 0;
            },
          ).catch(() => {
            done();
            this.goon = false;
          });
        }
      })
    },
    rowSave(row, done, loading) {
      let valid = this.validFunction(this.childPrdBomList);
      if (!valid) {
        this.goon = false;
        loading();
        return;
      }
      let children = this.childPrdBomList.map((item) => {
        if (item.id) {
          delete item.id;
        }
        return item;
      });
      row.dataSource = '1';
      let content = {...row, childPrdBomList: children};
      if (this.type == 'add') {
        product.bomAdd(content).then(
          () => {
            if (this.goon) {
              loading();
              for (let key in this.$refs.crud.value) {
                this.$refs.crud.value[key] = null;
              }
              this.childPrdBomList = [];
              this.childPrdBomList.length = 0;
              this.goon = false;
              this.onLoad(this.page);
            } else {
              this.onLoad(this.page);
              done();
            }
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          },
          (error) => {
            this.goon = false;
            loading();
            // console.log(error);
          }
        );
      } else if (this.type == 'edit') {

      } else if (this.type == 'copy') {

      }

    },
    rowUpdate(row, index, done, loading) {
      //行内的编辑事件触发
      // let children = this.childPrdBomList.map((item) => {
      //   if (item.id) {
      //     delete item.id;
      //   }
      //   return item;
      // });、
      let valid = this.validFunction(this.childPrdBomList);
      if (!valid) {
        loading();
        return;
      }
      // 复制新增
      if (this.copy) {
        let children = this.childPrdBomList.map((item) => {
          if (item.id) {
            delete item.id;
          }
          return item;
        });
        row.dataSource = '1';
        row.id = null;
        let content = {...row, childPrdBomList: children};
        product.bomAdd(content).then(
          () => {
            done();
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          },
          (error) => {
            loading();
            // console.log(error);
          }
        );
      } else {
        // 编辑保存
        let content = {...row, childPrdBomList: this.childPrdBomList};
        product.bomUpdate(content).then(
          () => {
            done();
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          },
          (error) => {
            loading();
            // console.log(error);
          }
        );
      }
    },
    rowDel(row) {
      //行内的删除事件触发
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return product.bomRemove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    showBomHistoryFn(row) {
      this.bomMainData = row
      this.bomHistory = true
    },
    handleDelete() {
      //多选删除
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let isApprove = false;
      isApprove = this.selectionList.some((item) => {
        return item.auditStatus != 1;
      });
      if (isApprove) {
        this.$message({
          type: 'error',
          message: '不可以删除审批中、已通过或被驳回的数据！',
        });
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return product.bomRemove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen() {
      let type = this.type
      this.childPrdBomList.length = 0;
      this.childPrdBomList = [];
      const column0 = this.findObject(this.option.group, 'materialGroupNo');
      column0.dicData.length = 0;
      column0.dicData = [];
      const column = this.findObject(this.option.group, 'bomNo');
      column.dicData.length = 0;
      column.dicData = [];

      if (['edit','copy','view'].includes(type)) {
        product.bomDetail(this.form.id).then((res) => {
          let data = res.data.data;
          this.childPrdBomList = data.childPrdBomList;
          let materialNoData = this.findObject(this.option.group, 'materialNo').dicData;
          if (materialNoData.findIndex((res) => res.value == this.form.materialNo) == -1) {
            materialNoData.unshift({
              label: this.form.materialName + '(' + this.form.materialNo + ')',
              value: this.form.materialNo,
            });
          }
          this.form = data;
          if (type == 'copy') {
            this.$set(this.form, 'materialNo', '');
          }
        });
      }
      if (type == 'view') {
        this.infoOption.menu = false;
        this.findObject(this.option.group, 'materialNo').disabled = true;
        this.findObject(this.option.group, 'bomMaterialType').display = false;
        this.findObject(this.option.group, 'materialGroupNo').display = false;
        this.findObject(this.option.group, 'bomNo').display = false;
        this.findObject(this.option.group, 'add').display = false;

      } else {
        this.infoOption.menu = true;
        this.findObject(this.option.group, 'materialNo').disabled = false;
        this.findObject(this.option.group, 'bomMaterialType').display = true;
        this.findObject(this.option.group, 'materialGroupNo').display = true;
        this.findObject(this.option.group, 'bomNo').display = true;
        this.findObject(this.option.group, 'add').display = true;
      }
      if (type == 'add') {
        this.$set(this.form, 'materialNo', '')
        this.$set(this.form, 'bomMaterialType', '')
        this.$set(this.form, 'materialGroupNo', '')
        this.$set(this.form, 'bomNo', '')
      }
    },
    beforeClose(done) {
      this.copy = false;
      done();
    },
    onLoad(page, params = this.query) {
      //加载table
      this.query.dataSource = '1';
      this.loading = true;
      Promise.all([
        product.bomList(page.currentPage, page.pageSize, Object.assign(params, this.query)),
        product.bomproductList({flag: 'bom'}),
      ]).then((res) => {
        let data1 = res[1].data.data;
        const column = this.findObject(this.option.group, 'materialNo');
        this.productList = data1;
        column.dicData = data1.map((item) => {
          return {
            label: item.materialName + '(' + item.materialNo + ')',
            value: item.materialNo,
          };
        });
        const data = res[0].data.data;
        // this.$refs.crud.setCurrentRow();
        this.page.total = data.total;
        this.data = data.records;

        this.loading = false;
        this.selectionClear();
        if (this.data.length > 0) {
          this.$nextTick(() => {
            this.$nextTick(() => {
              this.$refs.crud.setCurrentRow(this.data[0]);
            });
          });
        } else {
          this.BOMdata.length = 0;
          this.BOMdata = [];
        }
      });
      getUnitList().then((res) => {
        let data = res.data.data;
        const column = this.findObject(this.infoOption.column, 'unit');
        column.dicData = data.map((item) => {
          return {
            label: item.name + '(' + item.code + ')',
            value: item.code,
          };
        });
      });
    },
  },
};
</script>

<style>
.avue-crud__pagination {
  margin-top: 0;
  padding: 0;
}

.el-input-group__append {
  padding: 0 8px;
}
</style>
